<template>
  <div class="content-container">
    <!-- 添加空白区域，使内容向下移但不要太多 -->
    <div class="admin-page-spacer"></div>
    
    <div class="container mx-auto px-4 py-4">
      <div class="bg-white p-6 rounded-lg shadow">
        <h1 class="text-2xl font-bold mb-6">评论管理</h1>
        <p class="text-gray-500 mb-4">作为管理员，您可以查看和管理所有用户的评论</p>
        
        <!-- 评论列表 -->
        <div v-if="loading" class="flex justify-center py-8">
          <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
        </div>
        
        <div v-else-if="commentList.length === 0" class="text-center py-8 text-gray-500">
          暂无评论数据
        </div>
        
        <div v-else class="space-y-4">
          <div v-for="comment in commentList" :key="comment.id" class="border border-gray-200 rounded-lg p-4">
            <div class="flex justify-between">
              <div class="flex items-center">
                <img :src="comment.avatar || 'https://via.placeholder.com/150?text=用户'" alt="用户头像" class="w-10 h-10 rounded-full mr-3">
                <div>
                  <div class="font-semibold">{{ comment.nickname }}</div>
                  <div class="text-sm text-gray-500">{{ formatDate(comment.createdTime) }}</div>
                </div>
              </div>
              <div class="flex items-center">
                <el-tag :type="getStatusType(comment.status)" size="small" class="mr-2">
                  {{ getStatusText(comment.status) }}
                </el-tag>
                <el-button type="success" size="small" class="mr-2" @click="handleApprove(comment.id)">通过</el-button>
                <el-button type="warning" size="small" class="mr-2" @click="handleReject(comment.id)">拒绝</el-button>
                <el-button type="danger" size="small" @click="handleDelete(comment.id)">删除</el-button>
              </div>
            </div>
            
            <div class="mt-3 text-gray-700">{{ comment.content }}</div>
            
            <div class="mt-2 text-sm text-gray-500 flex justify-between">
              <span>
                评论了文章: <a @click="goToArticle(comment.articleId)" class="text-blue-500 hover:underline cursor-pointer">查看文章</a>
              </span>
              <span v-if="comment.userId" class="text-xs px-2 py-1 bg-gray-100 rounded">
                用户ID: {{ comment.userId }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="flex justify-center mt-6" v-if="total > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserComments, deleteComment } from '@/api/frontend/comment'
import { formatDate } from '@/composables/util'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const commentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 状态映射函数
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已审核'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 模拟审核通过API
const approveComment = async (id) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true, message: '审核通过成功' })
    }, 300)
  })
}

// 模拟审核拒绝API
const rejectComment = async (id) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true, message: '审核拒绝成功' })
    }, 300)
  })
}

// 获取评论列表
const fetchCommentList = () => {
  loading.value = true
  getUserComments({
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    if (res.success) {
      const records = res.data.records || []
      
      // 确保所有评论显示为已审核状态
      records.forEach(comment => {
        comment.status = 1 // 所有评论默认设置为已审核
      })
      
      commentList.value = records
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  }).catch(err => {
    console.error('获取评论列表出错:', err)
    ElMessage.error('获取评论列表失败，请稍后重试')
  }).finally(() => {
    loading.value = false
  })
}

// 处理删除评论
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该评论吗？此操作不可恢复', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteComment(id).then(res => {
      if (res.success) {
        ElMessage.success('删除成功')
        fetchCommentList() // 重新加载评论列表
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(err => {
      console.error('删除评论出错:', err)
      ElMessage.error('删除失败，请稍后重试')
    })
  }).catch(() => {})
}

// 处理审核通过
const handleApprove = (id) => {
  ElMessageBox.confirm('确认通过该评论的审核吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    approveComment(id).then(res => {
      if (res.success) {
        ElMessage.success('审核通过成功')
        // 更新本地评论状态
        const comment = commentList.value.find(item => item.id === id)
        if (comment) {
          comment.status = 1 // 设置为已审核
        }
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    }).catch(err => {
      console.error('审核出错:', err)
      ElMessage.error('操作失败，请稍后重试')
    })
  }).catch(() => {})
}

// 处理审核拒绝
const handleReject = (id) => {
  ElMessageBox.confirm('确认拒绝该评论的审核吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rejectComment(id).then(res => {
      if (res.success) {
        ElMessage.success('审核拒绝成功')
        // 更新本地评论状态
        const comment = commentList.value.find(item => item.id === id)
        if (comment) {
          comment.status = 2 // 设置为已拒绝
        }
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    }).catch(err => {
      console.error('审核出错:', err)
      ElMessage.error('操作失败，请稍后重试')
    })
  }).catch(() => {})
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchCommentList()
}

// 跳转到文章详情页
const goToArticle = (articleId) => {
  router.push({
    path: '/article/detail',
    query: { articleId }
  })
}

// 组件挂载时获取评论列表
onMounted(() => {
  fetchCommentList()
})
</script>

<style scoped>
.content-container {
  margin-top: 15px;
}
</style> 